//
//  TCMsgHandler.m
//
//  Created by dackli on 16/8/4.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "TCMsgHandler.h"
#import "TCLinkMicModel.h"
#import "UIView+LZCView.h"

@implementation AVIMMsgHandler


#pragma mark - AVIMMsgHandlerAble

- (instancetype)init {
    if (self = [super init]) {
        [[TIMManager sharedInstance] setMessageListener:self];
    }
    return self;
}

- (void)releaseIMRef {
    [[TIMManager sharedInstance] setMessageListener:nil];
}

// 发送点赞消息
// 返回值，true: 成功， false：表示超过频率限制，点赞失败
- (BOOL)sendLikeSenderInfo:(NSString *)senderInfo {
    // 点赞消息做频率限制：1秒/2次
    static TCFrequeControl *freqControl = nil;
    if (freqControl == nil) {
        freqControl = [[TCFrequeControl alloc] initWithCounts:2 andSeconds:1];
    }
    if (![freqControl canTrigger]) {
        return NO;
    }
    [self sendMessage:AVIMCMD_Custom_Like senderInfo:senderInfo msg:nil];
    
    return YES;
}

//发送文本消息
- (void)sendTextSenderInfo:(NSString *)senderInfo msg:(NSString*)msg {
    
    [self sendMessage:AVIMCMD_Custom_Text senderInfo:senderInfo msg:msg];
}

// 发送弹幕消息
- (void)sendDanmakuSenderInfo:(NSString *)senderInfo msg:(NSString *)msg {
    [self sendMessage:AVIMCMD_Custom_Danmaku senderInfo:senderInfo msg:msg];
}

// 向群成员发送自己进群消息
- (void)sendEnterLiveRoomSenderInfo:(NSString *)senderInfo {
    [self sendMessage:AVIMCMD_Custom_EnterLive senderInfo:senderInfo msg:nil];
}

// 向群成员发送自己退群消息
- (void)sendQuitLiveRoomSenderInfo:(NSString *)senderInfo {
    [self sendMessage:AVIMCMD_Custom_ExitLive senderInfo:senderInfo msg:nil];
}

// 发送礼物消息
- (void)sendGiftSenderInfo:(NSString *)senderInfo msg:(NSString *)msg {
    [self sendMessage:AVIMCMD_Custom_Gift senderInfo:senderInfo msg:msg];
}
// 发送禁言消息
- (void)sendBannedSenderInfo:(NSString *)senderInfo msg:(NSString *)msg {
    [self sendMessage:AVIMCMD_Custom_Banned senderInfo:senderInfo msg:msg];
}

// 发送关注主播消息
- (void)sendFavoritesSenderInfo:(NSString *)senderInfo msg:(NSString *)msg {
    [self sendMessage:AVIMCMD_Custom_Favorites senderInfo:senderInfo msg:msg];
}

// 发送踢人消息
- (void)sendRemoveAudienceSenderInfo:(NSString *)senderInfo msg:(NSString *)msg {
    [self sendMessage:AVIMCMD_Custom_RemoveAudience senderInfo:senderInfo msg:msg];
}

// 发送设置管理员消息
- (void)sendSetAdministratorSenderInfo:(NSString *)senderInfo msg:(NSString *)msg {
    [self sendMessage:AVIMCMD_Custom_SetAdministrator senderInfo:senderInfo msg:msg];
}

// 发送删除管理员消息
- (void)sendDeleteAdministratorSenderInfo:(NSString *)senderInfo msg:(NSString *)msg {
    [self sendMessage:AVIMCMD_Custom_DeleteAdministrator senderInfo:senderInfo msg:msg];
}


- (void)sendC2CSenderInfo:(NSString *)senderInfo toSenderInfo:(NSString *)toSenderInfo msg:(TIMElem *)msg succ:(void(^)())succ fail:(void(^)(int code,NSString *msg))fail {
    //    [self sendMessage:AVIMCMD_Custom_C2C senderInfo:senderInfo msg:msg];
    
//    if ([msg isKindOfClass:[TIMTextElem class]]) {
//        
//        TIMTextElem *textElem = (TIMTextElem *)msg;
//        NSDictionary* dict = @{@"userAction" : @(AVIMCMD_Custom_C2C), @"senderInfo" : TC_PROTECT_STR(senderInfo), @"msg" : TC_PROTECT_STR(textElem.text), @"receiverInfo": TC_PROTECT_STR(toSenderInfo)};
//        
//        NSData* data = [TCUtil dictionary2JsonData:dict];
//        NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        [textElem setText:content];
//        msg = textElem;
//        
//    } // 上面的文本解析过程应该必要，通知了私聊vc，私聊vc拥有逻辑
//    else if ([msg isKindOfClass:[TIMImageElem class]]) {
//        TIMTextElem *textElem = (TIMTextElem *)msg;
//        NSDictionary* dict = @{@"userAction" : @(AVIMCMD_Custom_C2C), @"senderInfo" : TC_PROTECT_STR(senderInfo), @"msg" : @"[图片]", @"receiverInfo": TC_PROTECT_STR(toSenderInfo)};
//        
//        NSData* data = [TCUtil dictionary2JsonData:dict];
//        NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        [textElem setText:content];
//        msg = textElem;
//    }
//    else if ([msg isKindOfClass:[TIMSoundElem class]]) {
//        
//    }
//    else if ([msg isKindOfClass:[TIMVideoElem class]]) {
//        TIMTextElem *textElem = (TIMTextElem *)msg;
//        NSDictionary* dict = @{@"userAction" : @(AVIMCMD_Custom_C2C), @"senderInfo" : TC_PROTECT_STR(senderInfo), @"msg" : @"[视频]", @"receiverInfo": TC_PROTECT_STR(toSenderInfo)};
//        
//        NSData* data = [TCUtil dictionary2JsonData:dict];
//        NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        [textElem setText:content];
//        msg = textElem;
//    }
//    else if ([msg isKindOfClass:[TIMFileElem class]]) {
//        
//    }
//    else if([msg isKindOfClass:[TIMCustomElem class]]) {
//        
//    }
    
    TIMMessage *timMsg = [[TIMMessage alloc] init];
    [timMsg addElem:msg];
    
    NSError *err;
    NSData *jsonData = [toSenderInfo dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
    
    NSLog(@"infoDict = %@", infoDict);
    
    TIMConversation *c2cConversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:infoDict[@"imId"]];
    
    
    [c2cConversation sendMessage:timMsg succ:^{
        DebugLog(@"sendMessage success, cmd:%d", AVIMCMD_Custom_C2C);
        succ();
    } fail:^(int code, NSString *msg) {
        DebugLog(@"sendMessage failed, cmd:%d, code:%d, errmsg:%@", AVIMCMD_Custom_C2C, code, msg);
        fail(code,msg);
    }];
}


- (void)sendC2CSenderInfo:(NSString *)senderInfo toSenderInfo:(NSString *)toSenderInfo msg:(NSString *)msg {
//    [self sendMessage:AVIMCMD_Custom_C2C senderInfo:senderInfo msg:msg];
    
    NSDictionary* dict = @{@"userAction" : @(AVIMCMD_Custom_C2C), @"senderInfo" : TC_PROTECT_STR(senderInfo), @"msg" : TC_PROTECT_STR(msg), @"receiverInfo": TC_PROTECT_STR(toSenderInfo)};
    
    NSData* data = [TCUtil dictionary2JsonData:dict];
    NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    TIMTextElem *textElem = [[TIMTextElem alloc] init];
    [textElem setText:content];
    
    TIMMessage *timMsg = [[TIMMessage alloc] init];
    [timMsg addElem:textElem];
    
    NSError *err;
    NSData *jsonData = [toSenderInfo dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                             options:NSJSONReadingMutableContainers
                                                               error:&err];
    
    NSLog(@"infoDict = %@", infoDict);
    
    TIMConversation * c2cConversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:infoDict[@"imId"]];
    
   
    
    [c2cConversation sendMessage:timMsg succ:^{
        DebugLog(@"sendMessage success, cmd:%d", AVIMCMD_Custom_C2C);
    } fail:^(int code, NSString *msg) {
        DebugLog(@"sendMessage failed, cmd:%d, code:%d, errmsg:%@", AVIMCMD_Custom_C2C, code, msg);
    }];
}

- (void)sendMessage:(AVIMCommand)cmd senderInfo:(NSString *)senderInfo msg:(NSString *)msgContent
{
    if ((AVIMCMD_Custom_Text == cmd || AVIMCMD_Custom_Danmaku == cmd) && msgContent.length == 0)
    {
        DebugLog(@"sendMessage failed, msg length is 0");
        return;
    }
    
    NSDictionary* dict = @{@"userAction" : @(cmd), @"senderInfo" : TC_PROTECT_STR(senderInfo), @"msg" : TC_PROTECT_STR(msgContent)};
    
    NSData* data = [TCUtil dictionary2JsonData:dict];
    NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    TIMTextElem *textElem = [[TIMTextElem alloc] init];
    [textElem setText:content];
    
    TIMMessage *timMsg = [[TIMMessage alloc] init];
    [timMsg addElem:textElem];
    
    [_chatRoomConversation sendMessage:timMsg succ:^{
        DebugLog(@"sendMessage success, cmd:%d", cmd);
    } fail:^(int code, NSString *msg) {
        DebugLog(@"sendMessage failed, cmd:%d, code:%d, errmsg:%@", cmd, code, msg);
    }];
}

#pragma mark - TIMMessageListener
- (void)onNewMessage:(NSArray *)msgs {
    // TODO 可以将onThread改为另外的线程
    [self performSelector:@selector(onHandleNewMessage:) onThread:[NSThread currentThread] withObject:msgs waitUntilDone:NO];
}

- (void)onHandleNewMessage:(NSArray *)msgs {
    for(TIMMessage *msg in msgs) {
        TIMConversationType conType = msg.getConversation.getType;
        
        switch (conType) {
            case TIM_C2C: {
                //目前只有连麦模块使用了C2C消息 -- 自己重新开方法出处理
//                if (NO == [[TCLinkMicModel sharedInstance] handleC2CMessageReceived:msg]) {
////                    //返回YES表示C2C消息已经被处理，否则可以继续给其它模块处理
//                }
                
                [self onRecvC2C:msg];

                break;
            }
            case TIM_GROUP: {
                if([[msg.getConversation getReceiver] isEqualToString:_groupId]) {
                    // 处理群聊天消息
                    // 只接受来自该聊天室的消息
                    [self onRecvGroup:msg];
                }
                break;
            }
            case TIM_SYSTEM: {
                // 这里获取的groupid为空，IMSDK的问题
                // 所以在onRecvGroupSystemMessage里面通过sysElem.group来判断
//                if ([[msg.getConversation getReceiver] isEqualToString:_groupId]) {
                    [self onRecvGroupSystemMessage:msg];
//                }
                break;
            }
            default:
                break;
        }
    }
}

- (void)onRecvGroupSystemMessage:(TIMMessage *)msg {
    for (int index = 0; index < [msg elemCount]; index++) {
        TIMElem *elem = [msg getElem:index];
        if ([elem isKindOfClass:[TIMGroupSystemElem class]]) {
            TIMGroupSystemElem *sysElem = (TIMGroupSystemElem *)elem;
            if ([sysElem.group isEqualToString:_groupId]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (_roomIMListener && [_roomIMListener respondsToSelector:@selector(onRecvGroupSystemMessage:)]) {
                        [_roomIMListener onRecvGroupSystemMessage:sysElem];
                    }
                });

            }
        }
    }
}

- (void)onRecvGroup:(TIMMessage *)msg {
    
    IMUserAble *userAble = [[IMUserAble alloc] init];
    
    for(int index = 0; index < [msg elemCount]; index++) {
        TIMElem *elem = [msg getElem:index];
        if([elem isKindOfClass:[TIMTextElem class]]) {
            // 消息总入口频率限制
            static TCFrequeControl *freqControl = nil;
            if (freqControl == nil) {
                freqControl = [[TCFrequeControl alloc] initWithCounts:20 andSeconds:1];
            }
            
            if (![freqControl canTrigger]) {
                return;
            }
            
            // 文本消息
            TIMTextElem *textElem = (TIMTextElem *)elem;
            NSString *msgText = textElem.text;
            NSDictionary* dict = [TCUtil jsonData2Dictionary:msgText];
            
            NSLog(@"%@", dict);
            
            NSDictionary *infoDict;
            
            if ([dict[@"userAction"] isEqual:@6]) {
                 infoDict = dict[@"senderInfo"];
            }
			else if([dict[@"userAction"] intValue] == 99){
				//这个if只是为了强行捕捉az的自定义退群消息
			}
            else {
				NSLog(@"I WAS HERERERERE");
            NSError *err;
            NSData *jsonData = [[dict valueForKey:@"senderInfo"] dataUsingEncoding:NSUTF8StringEncoding];
            infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                     options:NSJSONReadingMutableContainers
                                                                       error:&err];
            }
            
            NSLog(@"Json = %@", [dict valueForKey:@"senderInfo"]);
            
            if (dict)
            {
                if (dict[@"userAction"]) {
                    userAble.cmdType = [dict[@"userAction"] intValue];
                }
				
                userAble.imUserId = infoDict[@"imId"];
                userAble.imUserName = infoDict[@"nickname"];
                userAble.imUserIconUrl = infoDict[@"headpic"];
                userAble.level = [NSString stringWithFormat:@"%@", infoDict[@"level"]];
                userAble.uid = infoDict[@"uid"];
//                userAble.isVip = infoDict[@"is_enterprise"];
                msgText = dict[@"msg"];
				
				//强行捕捉az端的自定义退群消息
				if ([dict[@"userAction"] intValue] == 99) {
					userAble.cmdType = 3;
					NSDictionary *senderInfo = dict[@"senderInfo"];
					userAble.imUserId = senderInfo[@"imId"];
					userAble.imUserName = senderInfo[@"nickname"];
					userAble.imUserIconUrl = senderInfo[@"headpic"];
					userAble.level = [NSString stringWithFormat:@"%@", senderInfo[@"level"]];
					userAble.uid = senderInfo[@"uid"];
					//                userAble.isVip = infoDict[@"is_enterprise"];
					msgText = dict[@"msg"];
				}
            }
            else
            {
                TIMUserProfile *userProfile = [msg GetSenderProfile];
                if (userProfile) {
                    userAble.imUserId = userProfile.identifier;
                    userAble.imUserName = userProfile.nickname.length > 0 ? userProfile.nickname : userProfile.identifier;
                    userAble.imUserIconUrl = userProfile.faceURL;
                }
                userAble.cmdType = AVIMCMD_Custom_Text;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_roomIMListener) {
                    [_roomIMListener onRecvGroupSender:userAble textMsg:msgText];
                }
            });
        }
        else if([elem isKindOfClass:[TIMCustomElem class]]) {
            // 自定义消息
            TIMCustomElem* cele = (TIMCustomElem*)elem;
            NSString *dataStr = [[NSString alloc] initWithData:cele.data encoding:NSUTF8StringEncoding];
            DebugLog(@"datastr is:%@", dataStr);
        }
    }
}

- (void)onRecvC2C:(TIMMessage *)msg {
    
    NSLog(@"有人找你");
    
    [self sendNotification];
    
    /*
    for(int index = 0; index < [msg elemCount]; index++) {
        TIMElem *elem = [msg getElem:index];
        if([elem isKindOfClass:[TIMTextElem class]]) {
            // 消息总入口频率限制
//            static TCFrequeControl *freqControl = nil;
//            if (freqControl == nil) {
//                freqControl = [[TCFrequeControl alloc] initWithCounts:20 andSeconds:1];
//            }
//            
//            if (![freqControl canTrigger]) {
//                return;
//            }
//            
//            // 文本消息
//            TIMTextElem *textElem = (TIMTextElem *)elem;
//            NSString *msgText = textElem.text;
//            NSDictionary* dict = [TCUtil jsonData2Dictionary:msgText];
//            
//            NSLog(@"%@", dict);
//            
//            NSError *err;
//            NSData *jsonData = [[dict valueForKey:@"receiverInfo"] dataUsingEncoding:NSUTF8StringEncoding];
//            NSDictionary *infoDict = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                                     options:NSJSONReadingMutableContainers
//                                                                       error:&err];
//            
//            NSString *currId = [GetUserDefaule(USERINFO) valueForKey:@"user_id"];
//            if ([infoDict[@"imId"] isEqualToString:currId]) {
                //创建通知
                NSNotification *notification =[NSNotification notificationWithName:@"c2cNotification" object:nil userInfo:nil];
                //通过通知中心发送通知
                [[NSNotificationCenter defaultCenter] postNotification:notification];
//            }
        }
        // 上面的文本解析过程应该必要，通知了私聊vc，私聊vc拥有逻辑
        else if ([elem isKindOfClass:[TIMImageElem class]]) {
            [self sendNotification];
        }
        else if ([elem isKindOfClass:[TIMSoundElem class]]) {
            [self sendNotification];
        }
        else if ([elem isKindOfClass:[TIMVideoElem class]]) {
            [self sendNotification];
        }
        else if ([elem isKindOfClass:[TIMFileElem class]]) {
            [self sendNotification];
        }
        else if([elem isKindOfClass:[TIMCustomElem class]]) {
            [self sendNotification];
        }
    }*/
}

- (void)sendNotification {
    //创建通知
    NSNotification *notification =[NSNotification notificationWithName:@"c2cNotification" object:nil userInfo:nil];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)switchToLiveRoom:(NSString *)groupId
{
    _groupId = groupId;
    _chatRoomConversation = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:groupId];
}

//- (void)createLiveRoom:(void (^)(int, NSString *))handler
//{
//    __weak typeof(self) weakSelf = self;
//    [[TIMGroupManager sharedInstance] CreateAVChatRoomGroup:@"live" succ:^(NSString *groupId) {
//        DebugLog(@"createLiveRoom succ, groupId:%@", groupId);
//        //切换群会话的上下文环境
//        [weakSelf switchToLiveRoom:groupId];
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            handler(0, groupId);
//        });
//        
//    } fail:^(int code, NSString *msg) {
//        DebugLog(@"createLiveRoom failed, error:%d, msg:%@", code, msg);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            handler(code, nil);
//        });
//    }];
//}

- (void)createLiveRoomWithTitle:(NSString *)title coverPic:(NSString *)coverPic tagId:(NSString *)tagId handler:(void (^)(int, NSString *, NSString *, NSInteger, NSString *))handler
{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    // 请求头
    [session.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"] forHTTPHeaderField:@"Authorization"];
    
    __weak typeof(self) weakSelf = self;
    NSDictionary *parametersDict = @{@"title":TC_PROTECT_STR(title),
                                     @"cover":TC_PROTECT_STR(coverPic),
                                     @"tag_id":TC_PROTECT_STR(tagId),
                                     };
    NSLog(@"创建直播参数 = %@", parametersDict);
    /*
	 @"lat":[NSString stringWithFormat:@"%ld", (long)[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]],
	 @"lng":[NSString stringWithFormat:@"%ld", (long)[[NSDate dateWithTimeIntervalSinceNow:60] timeIntervalSince1970]],
	 @"intro":TC_PROTECT_STR(@"字数直播间"),
	 @"notice_time":TC_PROTECT_STR(@"暂定")
	 @"exp":[NSString stringWithFormat:@"%ld", (long)[[NSDate dateWithTimeIntervalSinceNow:60] timeIntervalSince1970]]
	 */
    
    UIViewController *currVC = [[[UIView alloc] init] topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    [MBProgressHUD showHUDAddedTo:currVC.view animated:YES];
    AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
	afn.requestSerializer = [AFHTTPRequestSerializer serializer];
	afn.responseSerializer = [AFJSONResponseSerializer serializer];
	afn.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
	
    // 请求头
    [afn.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"]forHTTPHeaderField:@"Authorization"];
	
	//将主播个性签名作为简介以供后面分享出去
	NSString *intro = GetUserDefaule(USERINFO)[@"intro"];
    NSDictionary *dict = @{@"title":TC_PROTECT_STR(title),
                           @"tag_id":TC_PROTECT_STR(tagId),
						   @"cover":TC_PROTECT_STR(coverPic),
						   @"iat":[NSString stringWithFormat:@"%ld", (long)[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]],
						   @"exp":[NSString stringWithFormat:@"%ld", (long)[[NSDate dateWithTimeIntervalSinceNow:60] timeIntervalSince1970]],
						   @"intro":TC_PROTECT_STR(intro),
						   @"notice_time":TC_PROTECT_STR(@"暂定")
                           };
    
    // JWT秘钥
    NSString *secret = JWTSecret;
    id<JWTAlgorithm> algorithm = [JWTAlgorithmFactory algorithmByName:@"HS256"];
    JWTBuilder *jwtBuilder = [JWTBuilder encodePayload:dict].secret(secret).algorithm(algorithm);
    NSString *jwtStr = [NSString stringWithFormat:@"%@", jwtBuilder.encode];
    
    [afn POST:APICreateLives parameters:@{@"jwt":jwtStr} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
        //        return [obj valueForKey:@"payload"];
        NSDictionary *liveDict = [[obj valueForKey:@"payload"] valueForKey:@"data"];
        NSLog(@"创建直播 success = %@", liveDict);
		[weakSelf switchToLiveRoom:liveDict[@"chatroom_id"]];
		dispatch_async(dispatch_get_main_queue(), ^{
			handler(0, liveDict[@"chatroom_id"], liveDict[@"push_url"], [liveDict[@"start_time"] intValue], [NSString stringWithFormat:@"%@", liveDict[@"id"]]);
		});
		
		/*目前后台设置的新的直播间模式为聊天室模式，此模式下再join会造成2次加入
        // 后台创建直播只是返回一个 chatRoom id 回来，需要前端自己进入房间
        //  申请加群
        [[TIMGroupManager sharedInstance] JoinGroup:liveDict[@"chatroom_id"] msg:nil succ:^{
            
            //切换群会话的上下文环境
            [weakSelf switchToLiveRoom:liveDict[@"chatroom_id"]];
            [MBProgressHUD hideHUDForView:currVC.view animated:YES];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(0, liveDict[@"chatroom_id"], liveDict[@"push_url"], [liveDict[@"start_time"] intValue], [NSString stringWithFormat:@"%@", liveDict[@"id"]]);
            });
        } fail:^(int code, NSString *msg) {
            [MBProgressHUD hideHUDForView:currVC.view animated:YES];
            DebugLog(@"createLiveRoom failed, error:%d, msg:%@", code, msg);
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(code, nil, nil, 0, 0);
            });
        }];
        */
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:currVC.view animated:YES];
        
        NSLog(@"创建直播 failure = %@", error);
        NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
        NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData:errorData options:kNilOptions error:nil];
        NSString *code = [NSString stringWithFormat:@"%@", serializedData[@"error_code"]];
		
		if([[GetUserDefaule(Token) valueForKey:@"role"] isEqualToString:@"1"]) {
			
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你尚未认证主播" preferredStyle:UIAlertControllerStyleAlert];
			[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				//                [currVC dismissViewControllerAnimated:YES completion:nil];
				//                [currVC.presentingViewController dismissViewControllerAnimated:YES completion:nil];
				[currVC.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
			}]];
			
			[currVC presentViewController:alert animated:YES completion:nil];
			
		}
        else if ([code isEqualToString:@"60005"]) {
            
            NSString *url = [APIUser stringByAppendingFormat:@"/%@/lives", [GetUserDefaule(USERINFO) valueForKey:@"user_id"]];
            
            [[NetworkTool sharedTool] requestWithName:@"进入直播间" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
                
                NSDictionary *liveDict = responseObject[@"data"];
                NSLog(@"\n进入直播间 成功 = %@", liveDict);
                
                // 后台创建直播只是返回一个 chatRoom id 回来，需要前端自己进入房间
                //  申请加群
                [[TIMGroupManager sharedInstance] JoinGroup:liveDict[@"chatroom_id"] msg:nil succ:^{
                    
                    //切换群会话的上下文环境
                    [weakSelf switchToLiveRoom:liveDict[@"chatroom_id"]];
                    [MBProgressHUD hideHUDForView:currVC.view animated:YES];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        handler(0, liveDict[@"chatroom_id"], liveDict[@"push_url"], [liveDict[@"start_time"] intValue], [NSString stringWithFormat:@"%@", liveDict[@"id"]]);
                    });
                } fail:^(int code, NSString *msg) {
                    [MBProgressHUD hideHUDForView:currVC.view animated:YES];
                    DebugLog(@"createLiveRoom failed, error:%d, msg:%@", code, msg);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        handler(code, nil, nil, 0, 0);
                    });
                }];
            }];
        }
    }];
}

- (void)deleteLiveRoom:(NSString *)groupId handler:(void (^)(int))handler
{
    [[TIMGroupManager sharedInstance] DeleteGroup:TC_PROTECT_STR(groupId) succ:^{
        DebugLog(@"deleteLiveRoom succ, groupId:%@", groupId);
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(0);
        });
        
    } fail:^(int code, NSString *msg) {
        DebugLog(@"deleteLiveRoom failed, error:%d, msg:%@", code, msg);
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(code);
        });
    }];
}

- (void)joinLiveRoom:(NSString *)groupId handler:(void (^)(int))handler
{
    __weak typeof(self) weakSelf = self;
    [[TIMGroupManager sharedInstance] JoinGroup:groupId msg:nil succ:^{
        DebugLog(@"joinGroup success,group id:%@", groupId);
        //切换群会话的上下文环境
        [weakSelf switchToLiveRoom:groupId];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(0);
        });
        
    } fail:^(int code, NSString *msg) {
        if (kError_HasBeenGroupMember == code)  //10013表示已经是群成员
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(0);
            });
        }
        else
        {
            DebugLog(@"joinGroup failed,group id:%@, code:%d, msg:%@", groupId, code, msg);
            dispatch_async(dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(code);
                });
            });
        }
    }];
}

- (void)quitLiveRoom:(NSString *)groupId handler:(void (^)(int))handler
{
    [[TIMGroupManager sharedInstance] QuitGroup:groupId succ:^{
        DebugLog(@"quitGroup success,group id:%@", groupId);
    } fail:^(int code, NSString *msg) {
        DebugLog(@"quitGroup failed,group id:%@", groupId);
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(code);
        });
        
    }];
}


@end



@implementation IMUserAble

@end

